import storage from '@system.storage'
import audio from '@system.audio'
/**
 * 页面参数处理
 */
async function page_param_handler(appInfo, pageInfo) {
  LOG('page_param_handler===================>', pageInfo.$page.query)
  await GLOBAL_UTILS.updateCommonData(pageInfo)
  if (Number(pageInfo.intent) == 0) {
    return
  }
  COMMON_REPORT_UTILS.set_attr('init_status', 0)
  //默认策略初始化状态  用于渠道用户进入获取新的策略配置
  TACTICS_SDK_UTILS.tactics_sdk_data.isTacticsSdkInit = false
  if (pageInfo.intent == 2 || pageInfo.intent == 3) {
    appInfo.utm_ad_id =
      pageInfo.$page.query.adid ||
      pageInfo.$page.query.aid ||
      pageInfo.$page.query.ad_id ||
      pageInfo.$page.query.campaign_id ||
      '' //广告计划id
    appInfo.utm_source =
      pageInfo.$page.query.ua ||
      pageInfo.$page.query.site ||
      pageInfo.$page.query.adgroup_id ||
      pageInfo.$page.query.encrypted_position_id ||
      pageInfo.$page.query.unionid ||
      '' //对外广告位编码
      ; (appInfo.utm_content =
        pageInfo.$page.query.cid ||
        pageInfo.$page.query.creativeid ||
        pageInfo.$page.query.content_id ||
        ''), //广告创意 id，长整型
        (appInfo.utm_campaign =
          pageInfo.$page.query.campaignid &&
            pageInfo.$page.query.campaignid !== '__CAMPAIGN_ID__'
            ? `${pageInfo.$page.query.campaignid}`.split(',')[0]
            : '') //广告组 id
    appInfo.channelId = $utils.getExchangeChannelId(pageInfo.channelId) //渠道id
    appInfo.linkId = pageInfo.linkId //链接id
    appInfo.intent = pageInfo.intent //deeplink 进入
    appInfo.materialType = pageInfo.materialType
      ? `${pageInfo.materialType}`
      : '' //素材分类
    appInfo.uniqueId = pageInfo.$page.query.uniqueId
    appInfo.hapKey = pageInfo.$page.query.hapKey
    appInfo.utm_term = pageInfo.$page.query.clickid
    appInfo.imei = pageInfo.$page.query.imei || ''
    appInfo.utm_medium = pageInfo.$page.query.rtype || ''
    appInfo.sourceId = pageInfo.$page.query.bookId || ''
  }

  if (pageInfo.intent == 2) {
    //deeplink
    appInfo.pageCodeInfo.pathUrl = 'hap链接'
    appInfo.pageCodeInfo.pageOrigin = 'CHANNEL_ROOT'
    TACTICS_SDK.setGlobalData('ts', pageInfo.ts)
  } else if (pageInfo.intent == 3) {
    //通知栏点击
    appInfo.pageCodeInfo.pathUrl = '通知栏'
    appInfo.pageCodeInfo.pageOrigin = 'NOTICE_ROOT'
  } else {
    // 桌面启动
    appInfo.pageCodeInfo.pathUrl = '桌面'
    appInfo.pageCodeInfo.pageOrigin = 'DESK_ROOT'
  }
  AD_SDK_UTILS.updataAdConfigData({ uploadFristPopClick: 0 })
  // 统计埋点SDK初始化
  COMMON_REPORT_UTILS.report_initSdk(appInfo)
  storage.get({ key: 'tacticsData' }).then((tacticsData) => {
    let number_of_visits = 1
    if (tacticsData.data) {
      let data = JSON.parse(tacticsData.data)
      number_of_visits = data.number_of_visits
        ? Number(data.number_of_visits) + 1
        : 1
    }
    // hap链接启动上报
    COMMON_REPORT_UTILS.hap_report(
      $utils.getSourceType(),
      number_of_visits + '',
      appInfo.deviceInfo.platformVersionCode + '',
      appInfo.imei,
      appInfo.oaid
    )
  })
}
/**
 * 获取banner广告数据
 */
let timerRefBanner = null
const getBannerAdConfig = async (_this) => {
  _this.bannerObj = null
  AD_SDK.destroyBannerAdv()
  _this.bannerObj = await AD_SDK.getSingleBanner(_this.nativeBoostGroupController.popShow, _this)
  const refBanner = TACTICS_SDK.getApplyConfig('ref_banner', 'n')
  console.log(refBanner, timerRefBanner, 'bannerScale------自动刷新')
  if (refBanner && !timerRefBanner) {
    timerRefBanner = setTimeout(() => {
      clearTimeout(timerRefBanner)
      timerRefBanner = null
      getBannerAdConfig(_this)
    }, refBanner)
  }
}

const pageShow = (_this) => {
  // 广告跳转回应用 后续操作
  AD_UTILS.viewShowHandler()
  if (_this.isJump) {
    _this.isJump = false
    _this.nativeBoostGroupController.startTimeout++
    GLOBAL_UTILS.updateCommonData(_this)
    _this.isAllowBackPress = true
    if (_this.bannerObj !== undefined) {
      getBannerAdConfig(_this)
    }
  }
}
const pageInit = async (_this) => {
  // 初始化数据
  await page_param_handler(_this.$app.$def, _this)
  // 初始化策略sdk
  let ad_init_res = await page_user_data_init(_this.$app.$def, _this)
  if (ad_init_res == 1) {
    _this.isShowBoostAd = TACTICS_SDK.getApplyConfig(_this.boostFlag, 'n', 3)
    if (_this.isShowBoostAd != 1) {
      // 初始化补量组件配置
      let _curBoostConfig = TACTICS_SDK_UTILS.initBoostGroupConfig(_this.pageDetail.pageCode)
      Object.assign(_this.nativeBoostGroupController, _curBoostConfig);
    } else {
      _this.isAllowBackPress = true
    }
  } else {
    LOG('sdk初始化失败--------------')
    _this.isAllowBackPress = true
  }
  if (_this.bannerObj !== undefined) {
    getBannerAdConfig(_this)
    _this.$watch('nativeBoostGroupController.popShow', 'isShowBannerHandle')
  }
  COMMON_REPORT_UTILS.page_show_report(_this.pathUrl)
}
const pageHide = (_this) => {
  AD_UTILS.viewHideHandler()
  _this.isJump = true
  _this.nativeBoostGroupController.stopTimeout++
  audio.stop()
  // 底通归零
  clearInterval(timerRefBanner)
  timerRefBanner = null
  AD_SDK.hideBannerAdv()
}
const pageBack = (_this) => {
  if (!_this.isAllowBackPress) {
    if (_this.backPressRefuseReport) return true
    _this.backPressRefuseReport = true
    COMMON_REPORT_UTILS.back_click_report('', '', '初始化拦截')
    return true
  }
  if (_this.videoBqtConfig.isShow) {
    _this.videoBqtConfig.backPressTimes++
    return true
  }
  if (!_this.nativeBoostGroupController.isShowBoostComp) {
    POP_TOOLS.noAd4UseEventHandler({ actionCode: 'PAGE_BACK', code: '' }, { ..._this.pageDetail }, _this.$app.$def)
    return true
  }
  if (!_this.nativeBoostGroupController.popShow) {
    _this.nativeBoostGroupController.popCode = ''
  }
  _this.nativeBoostGroupController.backPressTimes++
  return true
}
/**
 * 用户登录 以及广告sdk初始化
 */
function page_user_data_init(appInfo, pageInfo) {
  return new Promise(async (resolve) => {
    // 策略初始化
    await TACTICS_SDK_UTILS.tacticsSdkInit(appInfo)
    AD_SDK_UTILS.initAdInfo(
      (res) => {
        resolve(res)
      }
    )
    // 是否允许录屏 是1 否0
    const isSecure = TACTICS_SDK.getApplyConfig('whether_allow_screen_record', 'B')
    if (!isSecure) {
      // 默认为 false，允许截屏和录屏，为 true 时不允许截屏和录屏
      pageInfo.$page.setSecure(true)
    }
  })
}

export default {
  pageShow,
  pageInit,
  pageHide,
  pageBack,
  page_param_handler,
  page_user_data_init,
}
